package com.android.djlmapp.activity.kuandai;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.constraint.ConstraintLayout;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.android.djlmapp.R;
import com.android.djlmapp.activity.kaika.QianMingActivity;
import com.android.djlmapp.activity.kaika.ShiMingRengZhengActivity;
import com.android.djlmapp.activity.kaika.web.LianTongXieYiListActivity;
import com.android.djlmapp.activity.kuandai.base.KuanDaiBaseActivity;
import com.android.djlmapp.model.eventbus.FaceRzInfo;
import com.android.djlmapp.tools.global.PrefUtils;
import com.android.djlmapp.tools.global.ToastUtils;
import com.android.readcard.eventbus.Event;
import com.android.readcard.eventbus.EventCodes;
import com.bumptech.glide.Glide;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

/**
 * 加装宽带
 */
@RuntimePermissions
public class JiaZhuangKuanDaiActivity extends KuanDaiBaseActivity {

    @BindView(R.id.top_bac)
    ImageView topBac;
    @BindView(R.id.ll_top_back)
    LinearLayout llTopBack;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.home_iv_readpoint)
    ImageView homeIvReadpoint;
    @BindView(R.id.top_notes)
    ImageView topNotes;
    @BindView(R.id.iv_top_msg)
    ConstraintLayout ivTopMsg;
    @BindView(R.id.iv_top_set)
    ImageView ivTopSet;
    @BindView(R.id.iv_top_kf)
    ImageView ivTopKf;
    @BindView(R.id.tv_top_jump)
    TextView tvTopJump;
    @BindView(R.id.page_title_layout)
    ConstraintLayout pageTitleLayout;
    @BindView(R.id.kuandai_tv_address)
    TextView kuandaiTvAddress;
    @BindView(R.id.kuandai_buchong)
    EditText kuandaiBuchong;
    @BindView(R.id.tv_xzhm)
    TextView tvXzhm;
    @BindView(R.id.kk_tv_xzhm)
    TextView kkTvXzhm;
    @BindView(R.id.jzkd_phone)
    TextView jzkdPhone;
    @BindView(R.id.jzkd_tv_phone)
    EditText jzkdTvPhone;
    @BindView(R.id.tv_smrz)
    TextView tvSmrz;
    @BindView(R.id.kk_tv_smrz)
    TextView kkTvSmrz;
    @BindView(R.id.cl_shiming)
    ConstraintLayout clShiming;
    @BindView(R.id.tv_smname)
    TextView tvSmname;
    @BindView(R.id.kk_tv_name)
    TextView kkTvName;
    @BindView(R.id.kk_cl_name)
    ConstraintLayout kkClName;
    @BindView(R.id.tv_cardnum)
    TextView tvCardnum;
    @BindView(R.id.kk_tv_cardnum)
    TextView kkTvCardnum;
    @BindView(R.id.kk_cl_cardnum)
    ConstraintLayout kkClCardnum;
    @BindView(R.id.kk_iv_photo)
    ImageView kkIvPhoto;
    @BindView(R.id.cl_smrz_item)
    RelativeLayout clSmrzItem;
    @BindView(R.id.tv_lxhm)
    TextView tvLxhm;
    @BindView(R.id.ll_tv_lxhm)
    EditText llTvLxhm;
    @BindView(R.id.kk_qianming_photo)
    ImageView kkQianmingPhoto;
    @BindView(R.id.cl_qianming)
    ConstraintLayout clQianming;
    @BindView(R.id.cb_xieyi)
    CheckBox cbXieyi;
    @BindView(R.id.tv_ltxy)
    TextView tvLtxy;
    @BindView(R.id.dkd_scroll)
    ScrollView dkdScroll;
    @BindView(R.id.dkd_tv_submit)
    TextView dkdTvSubmit;
    @BindView(R.id.cl_select_tc)
    ConstraintLayout clSelectTc;
    @BindView(R.id.kk_tv_kdsm)
    TextView kkTvKdsm;
    @BindView(R.id.cl_tc_kdsm)
    ConstraintLayout clTcKdsm;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_jia_zhuang_kuan_dai);
        ButterKnife.bind(this);
        initView();

    }

    @Override
    protected void initView() {
        llTopBack.setVisibility(View.VISIBLE);
        ivTopMsg.setVisibility(View.GONE);
        ivTopSet.setVisibility(View.GONE);
        ivTopKf.setVisibility(View.VISIBLE);
        tvName.setText("家装宽带");
        clTcKdsm.setVisibility(View.GONE);
        initData();
    }

    @Override
    protected void initData() {
        kuandaiTvAddress.setText(kuandaiAddress);
        kuandaiBuchong.setText(kuandaiAddress);
        kuandaiBuchong.setSelection(kuandaiAddress.length());
    }

    @Override
    protected void receiveEvent(Event event) {
        switch (event.getCode()) {
            case EventCodes.EventFaceCode.A: // 实名认证
                // 用户上传的照片(正,反,手持,公安)
                phot_lists = PrefUtils.getInt("PHOT_LISTS", 0);
                FaceRzInfo data3 = (FaceRzInfo) event.getData();
                if (data3 != null) {
                    face_image = data3.getFace_image();
                    face_ok = data3.getFace_ok();
                    sfz_card = data3.getSfz_card();
                    sfz_name = data3.getSfz_name();
                    sfzPhoto = data3.getSfzPhoto();

                    clSmrzItem.setVisibility(View.VISIBLE);

                    if ("1".equals(face_ok)) {
                        kkTvSmrz.setText("已认证");
                        bluetoothName = PrefUtils.getString("BluetoothName", "");
                    } else if ("2".equals(face_ok)) {
                        kkTvSmrz.setText("待审核");
                        bluetoothName = PrefUtils.getString("BluetoothName", "");
                    } else {
                        kkTvSmrz.setText("请扫描进行认证");
                    }

                    kkTvSmrz.setTextColor(Color.BLACK);
                    kkTvName.setText(sfz_name);
                    kkTvCardnum.setText(sfz_card);
                    // 加载身份证照片
                    Glide.with(JiaZhuangKuanDaiActivity.this).load(sfzPhoto).into(kkIvPhoto);
                }
                break;
        }
    }

    @OnClick({R.id.cl_select_tc, R.id.cl_shiming, R.id.cl_qianming, R.id.tv_ltxy,R.id.dkd_tv_submit})
    public void onViewClicked(View view) {

        switch (view.getId()) {
            case R.id.cl_select_tc: // 选择套餐
                startActivityForResult(new Intent(JiaZhuangKuanDaiActivity.this, KuanDaiTaoCanActivity.class)
                        .putExtra("KDTYPE", kdtype), 120);
                break;
            case R.id.cl_shiming: //实名认证
                if (isKdtc) {
                    startActivity(new Intent(JiaZhuangKuanDaiActivity.this, ShiMingRengZhengActivity.class)
                            .putExtra("ISKUANDAI", true).putExtra("SPECID", taocanSpecId));
                } else {
                    ToastUtils.showShortToast(JiaZhuangKuanDaiActivity.this, "请先选择套餐");
                }
                break;
            case R.id.cl_qianming: // 签名
                startActivityForResult(new Intent(JiaZhuangKuanDaiActivity.this, QianMingActivity.class), 0);
                break;
            case R.id.tv_ltxy: // 联通协议
                // 联通协议
                startActivity(new Intent(JiaZhuangKuanDaiActivity.this,
                        LianTongXieYiListActivity.class));
                break;
            case R.id.dkd_tv_submit: // 提交
                jzPhone = jzkdTvPhone.getText().toString().trim();
                llTvLxhmSub = llTvLxhm.getText().toString().trim();
                dkdTvSubmit.setEnabled(false);
                if (isSubOrder()) {
                    // 显示键盘
                    JiaZhuangKuanDaiActivityPermissionsDispatcher.openCameraWithCheck(this);
                } else {
                    dkdTvSubmit.setEnabled(true);
                }
                break;
        }
    }

    /**
     * 判断是否可以提交
     *
     * @return
     */
    private boolean isSubOrder() {
        Log.e("项目异常matches", "------matches------" + llTvLxhmSub);
        boolean isSubMit = false;
        if (TextUtils.isEmpty(jzPhone)) {
            ToastUtils.showShortToast(JiaZhuangKuanDaiActivity.this,
                    "请输入原有号码");
            return isSubMit;
        }

        boolean matches1 = TextUtils.isDigitsOnly(jzPhone);
        if (!matches1 || jzPhone.length() != 11) {
            ToastUtils.showShortToast(JiaZhuangKuanDaiActivity.this,
                    "原有号码格式有误");
            return isSubMit;
        }
        if (!TextUtils.isEmpty(face_image) && face_image != null) {
            if (!TextUtils.isEmpty(llTvLxhmSub)) {
                boolean matches = TextUtils.isDigitsOnly(llTvLxhmSub);
                if (matches && llTvLxhmSub.length() == 11) {
                    if ("1".equals(sFlag)) {
                        // 先判断权限
                        // showContacts();
                        if (cbXieyi.isChecked()) {
                            isSubMit = true;
                        } else {
                            ToastUtils.showShortToast(JiaZhuangKuanDaiActivity.this,
                                    "请阅读开卡相关协议并同意");
                        }
                    } else {
                        ToastUtils.showShortToast(JiaZhuangKuanDaiActivity.this,
                                "请先签名");

                    }
                } else {
                    ToastUtils.showShortToast(JiaZhuangKuanDaiActivity.this,
                            "联系电话格式有误");
                }

            } else {
                ToastUtils.showShortToast(JiaZhuangKuanDaiActivity.this,
                        "请输入联系电话");
            }
        } else {
            ToastUtils.showShortToast(JiaZhuangKuanDaiActivity.this,
                    "请先实名认证");
        }
        return isSubMit;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 2) {
            if (data != null) {
                // 签名url
                String sName = data.getStringExtra("fileName");
                // 是否签名
                sFlag = data.getStringExtra("signFlag");
                // 签名带回的金额
                sMoney = data.getStringExtra("signMoney");

                Log.e("项目异常", "----getStringExtra--sMoney------" + sMoney);
                Log.e("项目异常", "----getStringExtra--sName------" + sName);
                if (!TextUtils.isEmpty(sName)) {
                    // 加载签名照片
                    ImageLoader.getInstance()
                            .displayImage(sName, kkQianmingPhoto, new DisplayImageOptions.Builder()
                                    .cacheInMemory(true)//默认会在内存缓存
                                    .cacheOnDisk(true)//默认会在硬盘缓存
                                    .displayer(new FadeInBitmapDisplayer(1000)).build());
                }
            } else {
                ToastUtils.showShortToast(JiaZhuangKuanDaiActivity.this, "未获取到签名");
            }
        } else if (resultCode == RESULT_OK) {
            if (requestCode == 120) {
                // 选套餐返回
                isKdtc = true;
                String taocanName = data.getStringExtra("TAOCAN_NAME");
                String taocanSulv = data.getStringExtra("TAOCAN_SULV");
                taocanSpecId = data.getStringExtra("TAOCAN_SPEC_ID");
                clTcKdsm.setVisibility(View.VISIBLE);
                kkTvKdsm.setText(taocanSulv);
                kkTvXzhm.setText(taocanName);
            }
        }
    }

    @NeedsPermission({Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION})
    void openCamera() {
        // 获取手机信息
        Log.e("项目异常", "openCamera权限: =================");
        dkdTvSubmit.setEnabled(true);
        getLocationPrem();
    }

    @SuppressLint("NeedOnRequestPermissionsResult")
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        JiaZhuangKuanDaiActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @OnShowRationale({Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION})
    void showCamera(final PermissionRequest request) {
        new AlertDialog.Builder(this)
                .setPositiveButton("允许", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(@NonNull DialogInterface dialog, int which) {
                        request.proceed();
                    }
                })
                .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(@NonNull DialogInterface dialog, int which) {
                        request.cancel();
                    }
                })
                .setCancelable(false)
                .setMessage("请允许获手机定位权限")
                .show();
    }

    @OnPermissionDenied({Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION})
    void denied() {
        Log.e("权限", "------denied------");
        //        loginBtnLogin.setEnabled(true);
        // 获取手机信息
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Log.e("项目异常", "denied权限: =================");
                getLocationPrem();
            }
        });
    }

    @OnNeverAskAgain({Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION})
    void askAgain() {
        Log.e("权限", "------askAgain------");
        //        loginBtnLogin.setEnabled(true);
        // 获取手机信息
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Log.e("项目异常", "askAgain权限: =================");
                getLocationPrem();
            }
        });
    }
}
